import axios from 'axios'
import Global  from '../config/global'
import CustomLoading from '../common/myLoading'
import MyPop from './myPop'
import LocalData from './localData'
var qs = require('qs');

/** 
 * 封装网络请求相关操作方法 
 **/
var NetTool = {}


axios.interceptors.request.use(function (config) {

  //设置通用请求头
  config.headers = {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Is-Admin'    : LocalData.getIsAdmin(),
    'Action-Ids'  : LocalData.getActionIds()
  };

  return config;
}, function (error) {
  return Promise.reject(error)
});

// 添加一个响应拦截器
axios.interceptors.response.use(function (response) {

  if(response.data.success){
    return response.data.result
  }else{

    console.log("请求错误：" + JSON.stringify(response))

    var messageStr = ""

    if(typeof(response) == 'string'){
      response = JSON.parse(response)
    }

    if(response.data.result.message == undefined){
       messageStr = "网络请求失败"
    }else{
       messageStr  = response.data.result.message
    }

    MyPop.alertBox("请求失败","失败原因：" + messageStr)
    CustomLoading.endLoading()
    return Promise.reject(0)
  }
 
},function (error) {
  return Promise.reject(error);
})

//标准GET请求
NetTool.getHttp = function(apiName, cb){
  axios.get(Global.httpServer+apiName).then(function(response) {
    cb(response)
  }).catch((err) => {
    
  })
}

//标准POST请求
NetTool.postHttp = function(apiName, params, cb){
  axios.post(Global.httpServer+apiName,qs.stringify(params)).then(function(response) {
    cb(response)
  }).catch((err) => {
    
  })
}

//原始POST请求
NetTool.systemApiPostHttp = function(apiName, params, cb){
  axios.post(Global.devServer + apiName,qs.stringify(params)).then(function(response) {
    cb(response)
  }).catch((err) => {
    
  })
}

export default NetTool